package packVistas;

import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JMenuItem;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

/**
 * this is a checkbox list for swing application
 * @author  yinzhiguo
 */
public class CheckboxList extends javax.swing.JPanel {
    
    private Vector<BooleanWrap> dataModel = new Vector<BooleanWrap>();

    private int columnWidth = 0;
    
    public CheckboxList( Object[] datas) {
         if(datas == null)
            throw new java.lang.IllegalArgumentException("datas is null!");
         int max = 0;
         for(Object o : datas)
         {
                BooleanWrap bw = new BooleanWrap(o);
                int a = bw.getLabel().length();
                if(max < a)
                    max = a;
                dataModel.add(bw);
         }
        columnWidth = max;
        initComponents();
        this.setPreferredSize(table.getPreferredSize());
    }
    
    public CheckboxList(ArrayList list) {
        if(list == null || list.isEmpty())
            throw new java.lang.IllegalArgumentException("list is null or empty!");
        
        int max = 0;
         for(Object o : list)
         {
                BooleanWrap bw = new BooleanWrap(o);
                int a = bw.getLabel().length();
                if(max < a)
                    max = a;
                dataModel.add(bw);
         }
        columnWidth = max;
        initComponents();
        this.setPreferredSize(table.getPreferredSize());
    }

  private JMenuItem getMenuItem(String id) {
        JMenuItem item = new javax.swing.JMenuItem();
        if("all".equals(id))
        {
            item.setText("å…¨é€‰");
        }else if("notAll".equals(id))
        {
            item.setText("å…¨ä¸�é€‰");
        }else if("reverse".equals(id))
        {
            item.setText("å��é€‰");
        }
        return item;
        
    }

    public ArrayList getSelectedData(){
        ArrayList i = new ArrayList();
        
        for(BooleanWrap bw : dataModel){
            if(bw.getChecked()){
                i.add(bw.getData());
            }
        }
        return i;
    }
     
    private TableModel getTableModel() {
        return new DataModel();
    }

   
     

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        popupMenu = new javax.swing.JPopupMenu();
        allMenuItem = getMenuItem("all");
        notAllMenuItem = getMenuItem("notAll");
        reverseMenuItem = getMenuItem("reverse");
        colText = new javax.swing.JTextField();
        scrollPane = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();

        allMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                allMenuItemActionPerformed(evt);
            }
        });
        popupMenu.add(allMenuItem);

        notAllMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                notAllMenuItemActionPerformed(evt);
            }
        });
        popupMenu.add(notAllMenuItem);

        reverseMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                reverseMenuItemActionPerformed(evt);
            }
        });
        popupMenu.add(reverseMenuItem);

        setLayout(new java.awt.BorderLayout());
        add(colText, java.awt.BorderLayout.PAGE_START);

        table.setModel(getTableModel());
        table.setComponentPopupMenu(popupMenu);
        setTableParam();
        scrollPane.setViewportView(table);

        add(scrollPane, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

           private void actionPerformOfButton(int type){
               if(!dataModel.isEmpty()){
                    for(BooleanWrap bw : dataModel)
                    {
                        if(type == 1){
                        bw.setChecked(Boolean.TRUE);
                        }else if(type == 2)
                        {
                            bw.setChecked(Boolean.FALSE);    
                        }else if(type == 3){
                            bw.setChecked(!bw.getChecked());
                        }
                    }
                    ((AbstractTableModel)table.getModel()).fireTableDataChanged();
                }
           }

private void allMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_allMenuItemActionPerformed
// TODO add your handling code here:
    actionPerformOfButton(1);
}//GEN-LAST:event_allMenuItemActionPerformed

private void notAllMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_notAllMenuItemActionPerformed
// TODO add your handling code here:
    actionPerformOfButton(2);
}//GEN-LAST:event_notAllMenuItemActionPerformed

private void reverseMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reverseMenuItemActionPerformed
// TODO add your handling code here:
    actionPerformOfButton(3);
}//GEN-LAST:event_reverseMenuItemActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem allMenuItem;
    private javax.swing.JTextField colText;
    private javax.swing.JMenuItem notAllMenuItem;
    private javax.swing.JPopupMenu popupMenu;
    private javax.swing.JMenuItem reverseMenuItem;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JTable table;
    // End of variables declaration//GEN-END:variables

    private void setTableParam() {
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
     //   table.setDragEnabled(false);
        table.setShowGrid(false);
        table.getTableHeader().setEnabled(false);
        
        //è®¾ç½®è¡¨å¤´ä¸�å�¯è§�
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setPreferredSize(new Dimension(0, 0));
        table.getTableHeader().setDefaultRenderer(renderer);
        
        
        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) {
                        return;
                    }
                    ListSelectionModel sm = (ListSelectionModel) e.getSource();
                    int row = sm.getLeadSelectionIndex();
                    if(row >=0){
                        BooleanWrap bw = dataModel.get(row);
                        colText.setText(bw.getLabel());
                    }
                }
            });
        
        DefaultTableColumnModel dtm = (DefaultTableColumnModel)table.getColumnModel();
        
        int count = dtm.getColumnCount();
        for(int i = 0; i < count; i++)
        {
            TableColumn tc = dtm.getColumn(i);
            tc.setResizable(false);
            if(i == 0){
                tc.setWidth(15);
                tc.setPreferredWidth(25);
            }else{
                tc.setWidth(columnWidth * 3);
                tc.setPreferredWidth(columnWidth * 10);
            }
        }
        ColumnColorTableCellRenderer ctlr = new ColumnColorTableCellRenderer();
        table.getColumnModel().getColumn(1).setCellRenderer(ctlr); 
    }

    
     class DataModel extends AbstractTableModel {
            private String[] columnNames = {"...", "..."};
            
            public Class getColumnClass(int columnIndex) {
                if(columnIndex == 0)
                    return Boolean.class;
                return String.class;
            }
            
            public String getColumnName(int column) {
                return columnNames[column];
            }
            public int getRowCount() {
                return dataModel.size();
            }
            
            public int getColumnCount() {
                return columnNames.length;
            }
            
            public Object getValueAt(int rowIndex, int colIndex) {
                BooleanWrap bw = dataModel.get(rowIndex);
                if(colIndex == 1)
                    return getDataLabel(bw.getData());
                else{
                    
                    return bw.getChecked();
                }
            }
            
        @Override
            public void setValueAt(Object value, int rowIndex, int colIndex) {
                if(colIndex == 0){
                    Boolean flag = (Boolean)value;
                    BooleanWrap bw = dataModel.get(rowIndex);
                    bw.setChecked(flag);
                    
                }
            }
            
        @Override
            public boolean isCellEditable(int rowIndex,
                    int columnIndex) {
                if(columnIndex == 0)
                    return true;
                return false;
            }
        }
    
     /**
      * æ­¤æ–¹æ³•èŽ·å¾—æ˜¾ç¤ºåœ¨listä¸­çš„æ•°æ�®çš„å­—ç¬¦ä¸²
      * å¦‚æœ‰éœ€è¦�ï¼Œéœ€é‡�å†™æ­¤æ–¹æ³•
      * @param data
      * @return
      */
    public Object getDataLabel(Object data){
        return data.toString();
    }
    
     class BooleanWrap{
        private Boolean checked = Boolean.FALSE;
        private Object data = null;
        
        public BooleanWrap(Object obj)
        {
            this.data = obj;
        }

        public Boolean getChecked() {
            return checked;
        }

        public void setChecked(Boolean checked) {
            this.checked = checked;
        }

        public Object getData() {
            return data;
        }

        public void setData(Object data) {
            this.data = data;
        }
        
        public String getLabel(){
            return (String)getDataLabel(this.getData());
        }
    }
    
}
